// packageA/pages/attendanceRuleAdd/attendanceRuleAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,    
    //考勤次数
    ruleNum: 2,
    //考勤次数选择框
    showNum:false,
    //考勤次数选择数据
    numList:[2,4],
    //考勤时间
    ruleTimeList:[{
      id:0,
      start:'',
      startBefore:'',
      startAfter:'',
      startBeforeStr:'未设置',
      startAfterStr:'未设置',
      end:'',
      endBefore:'',
      endAfter:'',
      endBeforeStr:'未设置',
      endAfterStr:'未设置'
    }],
    //时间选择框
    showTime:false,
    showRange:false,
    minTime: 0,
    maxTime: 23,  
    timeId:null,
    timeKey:null,
    //时间格式
    formatter (type, value) {
      if (type === 'hour') {
        return `${value} 点`
      } else if (type === 'minute') {
        return `${value} 分`
      }
      return value
    },
    formatter2 (type, value) {
      if (type === 'hour') {
        return `${value} 小时`
      } else if (type === 'minute') {
        return `${value} 分钟`
      }
      return value
    },
    //部门选择框
    showDepart:false,
    //部门选择数据
    departList:[],
    //搜索部门
    valueSearchDepart:'',
    //显示上下班时间信息框
    showInfo: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('考勤规则传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit: true
        })

        //获取修改的数据
        this.getInfo();
      }
    }
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let list=td.ruleTimeList;
    let editInfo=td.editInfo;

    //部门必填
    if(!editInfo.depart){
      Toast.fail('请选择部门');
      return;
    }
    
    //考勤规则名称必填
    let ruleName=obj.ruleName.trim();
    if(!this.formNotEmpty(ruleName,'ruleNameMessage','请输入考勤规则名称')){
      return;
    }

    //上下班时间必填
    let notTime=false;
    notTime=list.every((item)=>{
      return item.start && item.end;
    });

    if(!notTime){
      Toast.fail('请选择上下班时间');
      return;
    }
   
    //结束小于开始时，则下班标为次日
    for(let i=0;i<list.length;i++){
      //先全部置为false
      list[i].nextDayStart=false;
      list[i].nextDayEnd=false;

      if(list[i].end<list[i].start){
        list[i].nextDayEnd=true;
      }
    }
   
    //打卡多于2次时
    if(list.length>1){     
      //本次开始早于上次结束，则本次全标为次日
      for(let i=0;i<list.length;i++){
        if(i>0){
          if(list[i].start<list[i-1].end){
            list[i].nextDayStart=true;
            list[i].nextDayEnd=true;
          }
        }
      }

      //上次结束小于开始，则本次全标为次日
      for(let i=0;i<list.length;i++){
        if(i>0){
          if(list[i-1].end<list[i-1].start){
            list[i].nextDayStart=true;
            list[i].nextDayEnd=true;
          }
        }
      }

      //验证时间先后，上一次为次日，则后面的都不能大于前面的
      let flag=false;
      for(let i=0;i<list.length;i++){
        if(i>0){
          if(list[i-1].nextDayStart){
            if(list[i-1].end<list[i-1].start || list[i].start<list[i-1].end || list[i].end<list[i].start){
              flag=true;
              break;
            }            
          }
          
          if(!list[i-1].nextDayStart && list[i-1].nextDayEnd){
            if(list[i].start<list[i-1].end || list[i].end<list[i].start){
              flag=true;
              break;
            }         
          }

          if(!list[i-1].nextDayStart && !list[i-1].nextDayEnd && list[i].nextDayStart){
            if(list[i].end<list[i].start){
              flag=true;
              break;
            }       
          } 
        }
      }

      if(flag){
        Toast.fail({
          duration: 2000,
          message: '设置有错误，必须在上一个时间点之后'
        });
        return;
      }
    }

    //处理后赋值，显示信息确认框
    let ruleNames='editInfo.ruleName';
    this.setData({      
      [ruleNames]: ruleName,
      ruleTimeList: list,
      showInfo: true
    }) 
  },

  //确认信息后提交数据
  onConfirmInfo(){
    let td=this.data;  
    let departObj=app.globalData.userInfo.departObj[0];
    let ruleTimeList=td.ruleTimeList;
    let editInfo=td.editInfo;
    
    //处理考勤数据
    let ruleTime=[];  

    ruleTimeList.forEach(item => {
      let index=0;
      if(item.id==1){
        index=2;
      }
      ruleTime.push({
        index: index,
        clockInTime: item.start,
        beforeTime: item.startBefore ? item.startBefore : 0,
        afterTime: item.startAfter ? item.startAfter : 0,
        //是否跨天
        nextDay: item.nextDayStart
      });
      ruleTime.push({
        index: index+1,
        clockInTime: item.end,
        beforeTime: item.endBefore ? item.endBefore : 0,
        afterTime: item.endAfter ? item.endAfter : 0,
        nextDay: item.nextDayEnd
      });
    });
    
    //权限
    let authArr=[departObj.id, departObj.companyId, editInfo.departId, editInfo.regionId];
    let authSet=new Set(authArr);
    authArr=Array.from(authSet);

    let param={
      className:'clockRule',
      data:{
        requestToken: td.code,
        id: td.id,
        ruleName: editInfo.ruleName,
        ruleTime: ruleTime,
        departId: editInfo.departId,
        depart: editInfo.depart,
        dataAuthority: {
          depart: authArr
        }
      }
    }

    // console.log(param);
    // return;

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        
        //同步es数据
        if(td.isEdit){
          this.synchronClockRule(param.data);
        }

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
        
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'clockRule',
      data: {
        id:this.data.id,
        selectFields: ['id','ruleName','ruleTime','departId','depart']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];        
        
        //处理考勤数据
        let ruleTime=result.ruleTime;
        let ruleTimeList=[];
        let idx=0;

        for(let i=0;i<ruleTime.length/2;i++){
          ruleTimeList.push({
            id: i,
            start: ruleTime[idx].clockInTime,
            startBefore: ruleTime[idx].beforeTime,
            startBeforeStr: ruleTime[idx].beforeTime ? util.secondToFormat(ruleTime[idx].beforeTime/1000) : 0,
            startAfter: ruleTime[idx].afterTime,
            startAfterStr: ruleTime[idx].afterTime ? util.secondToFormat(ruleTime[idx].afterTime/1000) : 0,
            end: ruleTime[idx+1].clockInTime,
            endBefore: ruleTime[idx+1].beforeTime,
            endBeforeStr: ruleTime[idx+1].beforeTime ? util.secondToFormat(ruleTime[idx+1].beforeTime/1000) : 0,
            endAfter: ruleTime[idx+1].afterTime,
            endAfterStr: ruleTime[idx+1].afterTime ? util.secondToFormat(ruleTime[idx+1].afterTime/1000) : 0,
            nextDayStart: ruleTime[idx].nextDay,
            nextDayEnd: ruleTime[idx+1].nextDay,
          });

          if(ruleTime.length==4){
            idx=2;
          }
        }

        console.log('考勤规则回显');
        console.log(result);
        console.log(ruleTimeList);  

        this.setData({
          editInfo: result,
          //考勤次数
          ruleNum: ruleTime.length,
          //考勤数据回显
          ruleTimeList: ruleTimeList
        })
      }
    }).catch((error) => {
    })
  },
  
  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    console.log(prevPage.route);

    //从考勤组来的
    if(prevPage.route=='packageA/pages/attendanceGroupAdd/attendanceGroupAdd'){
      prevPage.getRuleList();
    }

    //从列表页来的
    if(prevPage.route=='packageA/pages/attendanceRules/attendanceRules'){
      prevPage.refreshListAndPage();
    }
  
    wx.navigateBack();
  },

  //显示考勤次数选择框
  onShowNum(){
    this.setData({ 
			showNum: true
    })   
  },

  //隐藏考勤次数选择框
  onCloseNum(){
    this.setData({ 
			showNum: false
    })
  },

  //确认考勤次数
  onConfirmNum(e){    
    let arr=[];
    let index=e.detail.index; 
    
    for(let i=0;i<index+1;i++){
      arr.push({
        id:i,
        start:'',
        startBefore:'',
        startAfter:'',
        startBeforeStr:'未设置',
        startAfterStr:'未设置',
        end:'',
        endBefore:'',
        endAfter:'',
        endBeforeStr:'未设置',
        endAfterStr:'未设置'
      });
    }

    this.setData({
      ruleNum: e.detail.value,
      ruleTimeList:arr      
    })

    this.onCloseNum();
  },

  //显示考勤时间
  onShowTime(e){
    let obj=e.currentTarget.dataset;

    this.setData({
      timeId: obj.id,
      timeKey: obj.key,
			showTime: true
    })
  },

  //隐藏考勤时间
  onCloseTime(){
    this.setData({ 
      showTime: false 
    })
  },
  
  //确认考勤时间
  onConfirmTime(e) {
    let ruleTimeList=this.data.ruleTimeList;
    let timeKey=this.data.timeKey;
    
    ruleTimeList.forEach(item => {
      item.nextDayStart=false;
      item.nextDayEnd=false;
		  if(item.id==this.data.timeId){
        item[timeKey]=e.detail;
		  }
    });

    this.setData({
      ruleTimeList: ruleTimeList,
      disabled: false
    })

    this.onCloseTime();
  }, 
  
  //显示打卡时段
  onShowRange(e){
    let obj=e.currentTarget.dataset;

    this.setData({
      timeId: obj.id,
      timeKey: obj.key,
			showRange: true
    })
  },

  //隐藏打卡时段
  onCloseRange(){
    this.setData({ 
      showRange: false 
    })
  },
  
  //确认打卡时段
  onConfirmRange(e) {
    let ruleTimeList=this.data.ruleTimeList;
    let timeKey=this.data.timeKey;
    let arr=e.detail.split(":"); 
    
    ruleTimeList.forEach(item => {
		  if (item.id==this.data.timeId){
        //打卡时段转化为毫秒
        let num = parseInt(arr[0])*60*60*1000 + parseInt(arr[1])*60*1000;

        //显示为文字
        let str=0;
        if(num){
          str=util.secondToFormat(num/1000);
        }

        item[timeKey]=num;
        item[timeKey+'Str']=str;        
		  }
    });  

    this.setData({
      ruleTimeList:ruleTimeList
    })

    this.onCloseRange();
  },

  //同步es数据
  synchronClockRule(obj){
    let param={
      ruleTime: obj.ruleTime,
      ruleName: obj.ruleName,
      id: obj.id,
      departId: obj.departId,
      depart: obj.depart,
    }
    CommonService.synchronClockRule(param).then(res=>{
    }).catch((error) => {
    })
  },

  //显示部门
  onShowDepart(){
    this.setData({
			showDepart: true
    })
    this.getDepartList();
  },

  //查询部门
  getDepartList(){
    this.setData({
      departList: []
    })

    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        searchAll: true,
        selectFields: ['id','name','regionId','fid']
      }
    }

    //模糊查询
    if(this.data.valueSearchDepart){
      param.data.name='%' + this.data.valueSearchDepart + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: {
              id: item.id,
              name: item.name
            }
          });
        });
        this.setData({
          departList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏部门
  onCloseDepart(){
    this.setData({
      showDepart: false,
      valueSearchDepart:''
    })
  },

  //确认部门
  onConfirmDepart(e){
    let departId='editInfo.departId';
    let depart='editInfo.depart';
    let regionId='editInfo.regionId';
    let obj=e.detail.value.obj;
   
    this.setData({
      [departId]: e.detail.value.id,
      [depart]: e.detail.value.obj,
      //项目的大区(无大区取上级)存入工牌的数据权限
      [regionId]: obj.regionId ? obj.regionId : obj.fid,
      disabled: false
    })

    this.onCloseDepart();
  },

  //搜索部门
  onChangeDepartVal(e){
    this.setData({
      valueSearchDepart: e.detail
    })
    this.getDepartList();
  },
  
  //隐藏上下班信息框
  onCloseInfo(){
    this.setData({
      showInfo: false,
      disabled: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})